
package com.yadong.smarthome.controldevice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.yadong.smarthome.controldevice.VoiceListenService.MessageListener;
import com.yadong.smarthome.controldevice.VoiceListenService.MyBinder;
import com.yadong.smarthome.controldevice.connectionimpl.DeviceInfoManagerImpl;
import com.yadong.smarthome2.protocol2.Utils;
import com.yadong.smarthome2.protocol2.wificlient.SocketServerService;

public class MainActivity extends Activity implements MessageListener, ServiceConnection{
    private static final int MSG_UPDATE_UI = 1;
    private static final int MSG_START_LISTEN = 2;
    private static final int MSG_UPDATE_TEXT = 3;

    private float mLastX;
    private float mLastY;
    private float mLastZ;
    private TextView mText;
    private TextView mText2;
    private SensorManager mSensorManager;
    private VoiceListenService mVoiceListenService;
    private boolean mIsListen = false;
    private View mView;
    private SocketServerService mSocketServerService;
    private DeviceInfoManagerImpl mDeviceManagerImpl;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDeviceManagerImpl = new DeviceInfoManagerImpl();
        mText = (TextView) findViewById(R.id.text);
        mText2 = (TextView) findViewById(R.id.text2);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(mSensorListener, sensor,SensorManager.SENSOR_DELAY_NORMAL);
        Intent intent = new Intent(this, VoiceListenService.class);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
        mView = findViewById(R.id.btn);
        findViewById(R.id.btn_on).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mSocketServerService.sendDataToClient(
                Utils.createResultWithKeyValue("receive_message", "开灯"));
            }
        });
        findViewById(R.id.btn_off).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mSocketServerService.sendDataToClient(
                        Utils.createResultWithKeyValue("receive_message", "关灯"));
            }
        });
        updateListenState(false);
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        }

        @Override
        public void onServiceConnected(ComponentName arg0, IBinder binder) {
            mVoiceListenService = ((MyBinder)binder).getService();
            mVoiceListenService.setMessageListener(MainActivity.this);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(mSensorListener);
        unbindService(mServiceConnection);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = SocketServerService.createServerInIntent(this);
        startService(intent);
        bindService(intent, this, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(this);
    }

    public void onServiceConnected(ComponentName name, IBinder service) {
        mSocketServerService = ((SocketServerService.MyBinder) service).getService();
        mSocketServerService.addSocketServerMessageListener(null);
        mSocketServerService.addSocketServerRequestListener(null);
        mSocketServerService.setDeviceInfoManager(mDeviceManagerImpl);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

    private Handler mHanlder = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_UI:
                    mText.setText("X:" + mLastX + " Y:" + mLastY + " Z:" + mLastZ);
                    break;
                case MSG_START_LISTEN:
                    mVoiceListenService.startListen();
                    updateListenState(true);
                    break;
                case MSG_UPDATE_TEXT:
                    String message = (String)msg.obj;
                    mText2.setText(message);
                    mSocketServerService.sendDataToClient(
                            Utils.createResultWithKeyValue("receive_message", message));
                default:
                    break;
            }
        };
    };

    private void updateListenState(boolean listen) {
        mIsListen = listen;
        if (listen) {
            mView.setBackgroundColor(0xff00ff00);
        } else {
            mView.setBackgroundColor(0xffff0000);
        }
    }

    private SensorEventListener mSensorListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor == null) {  
                return;
            }  

            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {  
                mLastX = event.values[SensorManager.DATA_X];  
                mLastY = event.values[SensorManager.DATA_Y];  
                mLastZ = event.values[SensorManager.DATA_Z];  
                String sX = String.valueOf(mLastX);  
                String sY = String.valueOf(mLastY);  
                String sZ = String.valueOf(mLastZ);  
                Message message = mHanlder.obtainMessage(MSG_UPDATE_UI);
                message.sendToTarget();
      
                if (mLastX <= 1 && mLastY >= 8 && mLastZ <= 5) {
                    if (!mIsListen) {
                        Message startMessage = mHanlder.obtainMessage(MSG_START_LISTEN);
                        mHanlder.sendMessageDelayed(startMessage, 500);
                    }
                } else {
                    if (mIsListen) {
                        stopListen();
                    }
                }
            } 
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub
            
        }
    };

    private void stopListen() {
       mVoiceListenService.stopListen();
       updateListenState(false);
    }

    @Override
    public void onNewMessageReceive(String message) {
        System.out.println("receive messsage:" + message);
        updateListenState(false);
        Message startMessage = mHanlder.obtainMessage(MSG_UPDATE_TEXT);
        startMessage.obj = message;
        startMessage.sendToTarget();
    }

}
